package foster_sql

import (
	"my-systems/pet-system/internal/db"
	"my-systems/pet-system/internal/models"
)

// 检查用户的宠物是否有寄养记录
func CheckFoster(uid int, pid uint) (bool, error) {
	var count int64
	err := db.DB.Model(&models.Foster{}).Where("user_id = ? AND pet_id = ?", uid, pid).Count(&count).Error
	if err != nil { // 有错误，预测有寄养记录，返回错误信息
		return true, err
	}
	return count != 0, nil
}

// 检查用户是否有寄养记录
func CheckFosterByID(uid int, id int) (bool, error) {
	var count int64
	err := db.DB.Model(&models.Foster{}).Where("user_id = ? AND id = ?", uid, id).Count(&count).Error
	if err != nil { // 有错误，预测有寄养记录，返回错误信息
		return true, err
	}
	return count != 0, nil
}

func AddFoster(foster *models.Foster) error {
	err := db.DB.Create(foster).Error
	if err != nil {
		return err
	}
	return nil
}

func UpdateFoster(uid int, pid uint, tmp *models.Foster) error {
	err := db.DB.Model(&models.Foster{}).Where("user_id = ? AND pet_id = ?", uid, pid).Updates(tmp).Error
	if err != nil {
		return err
	}
	return nil
}

func DeleteForster(uid int, id uint) error {
	err := db.DB.Model(&models.Foster{}).Where("user_id = ? AND id = ?", uid, id).Delete(&models.Foster{}).Error
	return err
}

func GetFosters(uid int) ([]*models.Foster, error) {
	var fosters []*models.Foster
	err := db.DB.Where("user_id = ?", uid).Find(&fosters).Error
	return fosters, err
}

func GetFosterByID(uid int, idInt int) ([]*models.Foster, error) {
	var fosters []*models.Foster
	err := db.DB.Where("user_id = ? AND id = ?", uid, idInt).Find(&fosters).Error
	return fosters, err
}
